﻿namespace Api.Controllers;

/// <summary>
/// 角色
/// </summary>
/// <param name="roleBLL"></param>
/// <param name="operationLogBLL"></param>
[Route("api/[controller]/[action]")]
[ApiController]
[Authorize]
public class RoleController(IRoleBLL roleBLL, IOperationLogBLL operationLogBLL) : BaseController(operationLogBLL)
{
    private readonly IRoleBLL _roleBLL = roleBLL;

    #region 获取角色下拉框数据
    /// <summary>
    /// 获取角色下拉框数据
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    public async Task<ResultModel<List<Role>>> GetRoleDownListAsync()
    {
        return await OperationExecuteReturnDataAsync(_roleBLL.GetDownListAsync);
    }
    #endregion

    #region 获取角色列表
    /// <summary>
    /// 获取角色列表
    /// </summary>
    /// <returns></returns>
    [HttpPost]
    public async Task<ResultModel<List<RoleVM>>> GetList([FromBody] RolePageQueryRM queryRM)
    {
        var roleList = await _roleBLL.GetPageListAsync(queryRM);
        var ret = new ResultModel<List<RoleVM>>
        {
            data = roleList,
            count = roleList != null ? roleList.Count : 0,
        };
        return ret;
    }
    #endregion

    #region 根据角色获取功能权限列表
    /// <summary>
    /// 根据角色获取功能权限列表
    /// </summary>
    /// <param name="roleId">角色id 必填</param>
    /// <returns></returns>
    [HttpGet]
    public async Task<ResultModel<List<Feature>>> GetFeatureListByRoleId(int roleId)
    {
        return await OperationExecuteReturnDataAsync(async () =>
        {
            return await _roleBLL.GetFeatureListByRoleIdAsync(roleId);
        });
    }
    #endregion

    #region 获取功能/菜单树
    /// <summary>
    /// 获取功能/菜单树
    /// </summary>
    /// <param name="roleId">角色id 必填</param>
    /// <returns></returns>
    [HttpGet]
    public async Task<ResultModel<List<FeatureTree>>> GetFeatureTrees(int roleId)
    {
        return await OperationExecuteReturnDataAsync(async () =>
        {
            return await _roleBLL.GetFeatureTreesAsync(roleId);
        });
    }
    #endregion

    #region 新建角色
    /// <summary>
    /// 新建角色
    /// </summary>
    /// <param name="createRM">必填：Name、FeatureIdList、Enable</param>
    /// <returns></returns>
    [HttpPost]
    public async Task<ResultModel> AddAsync([FromBody] RoleCreateRM createRM)
    {
        return await OperationExecuteCustomAsync(async () =>
        {
            return await _roleBLL.AddAsync(createRM);
        }, new AddOperationLogInput { Content = $"新建[角色]--{createRM.Name}" });
    }
    #endregion

    #region 编辑角色
    /// <summary>
    /// 编辑角色
    /// </summary>
    /// <param name="updateRM">必填：ID、Name、FeatureIdList、Enable</param>
    /// <returns></returns>
    [HttpPost]
    public async Task<ResultModel> UpdateAsync([FromBody] RoleUpdateRM updateRM)
    {
        return await OperationExecuteCustomAsync(async () =>
        {
            return await _roleBLL.UpdateAsync(updateRM);
        }, new AddOperationLogInput { Content = $"编辑[角色]--{updateRM.Name}" });
    }
    #endregion

    #region 删除角色
    /// <summary>
    /// 删除角色
    /// </summary>
    /// <param name="id">主键 必填</param>
    /// <returns></returns>
    [HttpGet]
    public async Task<ResultModel> Delete(int id)
    {
        var resultModel = new ResultModel();
        var role = await _roleBLL.GetRoleByIdAsync(id);
        if (role == null || role.Id <= 0)
        {
            resultModel.code = -1;
            resultModel.msg = "角色不存在";
            return resultModel;
        }
        return await OperationExecuteCustomAsync(async () =>
        {
            string resMsg = await _roleBLL.DeleteByIdAsync(id);
            if (resMsg == "R_INUSED")
            {
                resultModel.code = -1;
                resultModel.msg = "角色被使用，无法删除";
                return resultModel;
            }

            if (resMsg == "R_NOTEXIST")
            {
                resultModel.code = -1;
                resultModel.msg = "角色不存在";
                return resultModel;
            }

            resultModel.code = 1;
            return resultModel;
        }, new AddOperationLogInput { Content = $"删除[角色]--{role.Name}" });
    }
    #endregion

    #region 设置角色状态
    /// <summary>
    /// 设置角色状态
    /// </summary>
    /// <param name="rm"></param>
    [HttpPost]
    public async Task<ResultModel> SetRoleEnableByIdsAsync([FromBody] SetEnableRM rm)
    {
        var result = new ResultModel();
        var roleList = await _roleBLL.GetListAsync(x => rm.Ids.Contains(x.Id));
        if (roleList == null || !roleList.Any())
        {
            result.code = -1;
            result.msg = "未获取到角色！";
            return result;
        }
        var rolenames = string.Join("、", roleList.Select(x => x.Name));
        return await OperationExecuteCustomAsync(async () =>
        {
            var ret = await _roleBLL.SetRoleEnableByIdsAsync(rm);
            if (ret.code == 1)
            {
                result.code = 1;
                result.msg = "操作成功";
                result.data = true;
            }
            else
            {
                result.code = -1;
                result.msg = ret.msg;
            }
            result.data = ret.data;
            return result;
        }, new AddOperationLogInput { Content = rm.Enable == 1 ? $"启用[角色]--{rolenames}" : $"禁用[角色]--{rolenames}" });
    }
    #endregion

    #region 查询已授权用户
    /// <summary>
    /// 查询已授权用户
    /// </summary>
    /// <param name="roleId">角色id 必填</param>
    /// <returns></returns>
    [HttpGet]
    public async Task<ResultModel<List<SelectedUserVM>>> GetAssociatedUserByRoleIdAsync(int roleId)
    {
        return await OperationExecuteReturnDataAsync(async () =>
        {
            return await _roleBLL.GetAssociatedUserByRoleIdAsync(roleId);
        });
    }
    #endregion

    #region 获取角色详情
    /// <summary>
    /// 获取角色详情
    /// </summary>
    /// <param name="id">角色id 必填</param>
    /// <returns></returns>
    [HttpGet]
    public async Task<ResultModel<RoleDetailVM>> GetDetailAsync(int id)
    {
        return await OperationExecuteReturnDataAsync(async () =>
        {
            return await _roleBLL.GetDetail(id);
        });
    }
    #endregion

    #region 关联用户
    /// <summary>
    /// 关联用户
    /// </summary>
    /// <param name="rm"></param>
    [HttpPost]
    public async Task<ResultModel> BindUserAsync([FromBody] BindUserRM rm)
    {
        var result = new ResultModel();
        var role = await _roleBLL.GetAsync(x => x.Id == rm.RoleId);
        if (role == null || role.Id <= 0)
        {
            result.code = -1;
            result.msg = "未获取到角色！";
            return result;
        }
        return await OperationExecuteCustomAsync(async () =>
        {
            var ret = await _roleBLL.BindUser(rm);
            if (ret.code == 1)
            {
                result.code = 1;
                result.msg = "操作成功";
                result.data = true;
            }
            else
            {
                result.code = -1;
                result.msg = ret.msg;
            }
            result.data = ret.data;
            return result;
        }, new AddOperationLogInput { Content = $"关联用户--{role.Name}({rm.UserIds.Count})" });
    }
    #endregion
}
